
import { MoveBody } from "./MoveBody";
import { IMoveWorld } from "./IMoveWorld";


/**
 * 无缝循环使用的地面处理
 */

export default class MoveGround {

    protected _objectList: MoveBody[] = []
    protected _world: IMoveWorld;

    setWorld(w: IMoveWorld) {
        this._world = w;
    }

    add(element: MoveBody) {
        let index = this._objectList.length;
        this._objectList[index] = element;
        console.log(' element.width * index ', element.getWidth() * index)
        this._objectList[index].setX(element.getWidth() * index)
    }

    start(objectList: MoveBody[]) {
        for (let index = 0; index < objectList.length; index++) {
            const element = objectList[index]
            this.add(element)
        }
    }


    update(dt: number) {
        let person = this._world.getMoveBody();
        if (person && person.getSpeedX() != 0) {
            let camera = this._world.getCamera();
            let spx = person.getSpeedX();
            let first = this._objectList[0]
            let tail = this._objectList[this._objectList.length - 1]
            if (spx > 0) {
                if (first.getX() + first.getWidth() < camera.getX()) {
                    this._objectList.push(this._objectList.shift())
                    first.setX(tail.getX() + first.getWidth())
                }
            } else if (spx < 0) {
                if (tail.getX() > camera.getX() + camera.getWidth()) {
                    tail.setX(first.getX() - tail.getWidth())
                    this._objectList.unshift(this._objectList.pop())
                }
            }
        }

    }


}
